package com.shengqi.xinnongren.work.ui.user.fragments;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shengqi.xinnongren.R;
import com.shengqi.xinnongren.common.base.BaseMvpFragment;
import com.shengqi.xinnongren.common.utils.ImageUtils;
import com.shengqi.xinnongren.common.utils.ToastHelper;
import com.shengqi.xinnongren.common.widgets.CustomDialog;
import com.shengqi.xinnongren.work.event.RefreshEvent;
import com.shengqi.xinnongren.work.ui.goods.activities.ChoosePayTypeActivity;
import com.shengqi.xinnongren.work.ui.user.activities.ApplyRefundActivity;
import com.shengqi.xinnongren.work.ui.user.activities.CommitCommentActivity;
import com.shengqi.xinnongren.work.ui.user.activities.OrderDetailsActivity2;
import com.shengqi.xinnongren.work.ui.user.activities.RefundDetailsActivity;
import com.shengqi.xinnongren.work.ui.user.model.OrderBean;
import com.shengqi.xinnongren.work.ui.user.presenter.OrderListPresenter;
import com.shengqi.xinnongren.work.ui.user.view.OrderListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class OrderListFragment extends BaseMvpFragment<OrderListView, OrderListPresenter> implements OrderListView {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.rv_order_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.ll_empty_view)
    LinearLayout ll_empty_view;

    private String type;
    private int pageIndex = 0;

    private OrderListAdapter mAdapter;
    private List<OrderBean> mList;

    @Override
    protected int setLayoutResource() {
        return R.layout.fragment_order_list;
    }

    @Override
    protected void lazyLoadData() {
        mRefreshLayout.autoRefresh();
    }

    private void getData(boolean isLoadMore) {
        if (isLoadMore) {
            pageIndex++;
        } else {
            pageIndex = 0;
        }
        getPresenter().getOrderList(type, pageIndex);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()) {
            mRefreshLayout.autoRefresh();
        }
    }

    @Override
    protected void initView() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            type = arguments.getString("type");
        }
        mList = new ArrayList<>();
        mAdapter = new OrderListAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));


        mRefreshLayout.setOnRefreshListener(refreshLayout -> getData(false));

        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> getData(true));
    }


    @Override
    protected void initData() {

    }

    @Override
    protected OrderListPresenter createPresenter() {
        return new OrderListPresenter();
    }

    @Override
    public void showLoadingView() {
    }

    @Override
    public void hideLoadingView() {
        resetRefreshLayout();
    }


    @Override
    public void onNetworkError() {
        hideLoadingDialog();
        resetRefreshLayout();
    }

    private void resetRefreshLayout() {
        mRefreshLayout.finishRefresh().finishLoadMore();
    }

    @Override
    public void showRequestFailed(String message) {
        resetRefreshLayout();
        ToastHelper.getInstance(
                getContext()).showWarn(message);
    }

    @Override
    public void showOrderList(List<OrderBean> list) {
        resetRefreshLayout();
        if (pageIndex == 0)
            mList.clear();
        mList.addAll(list);
        ll_empty_view.setVisibility(mList.size() > 0 ? View.GONE : View.VISIBLE);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showCancelOrderRes(String message) {
        ToastHelper.getInstance(getContext()).showSucceed(message);
        getData(false);
    }

    @Override
    public void showConfirmOrderRes(String message) {
        ToastHelper.getInstance(getContext()).showSucceed(message);
        getData(false);
    }


    class OrderListAdapter extends RecyclerView.Adapter<OrderListAdapter.Holder> {
        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_order_list, parent, false));
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {

            OrderBean bean = mList.get(position);
            holder.mTvOrderSn.setText(bean.getNo());
            holder.mTvOrderStatus.setText(bean.getStatusName());
            holder.mTvOrderTotalMoney.setText(String.format("￥%s", bean.getPayAmount()));
            holder.mTvGoodsNum.setText(String.format("共%s件", bean.getCommodityNum()));
            holder.mTvOrderTime.setText(bean.getAddTime());

            //[0 取消订单 1确认支付 2确认收货 3提醒发货 4待评价 5查看详情 6申请退款 7退款详情 ]
            String operation = bean.getOperation();
            if (operation != null) {
                holder.tvOrderCancel.setVisibility(operation.contains("0") ? View.VISIBLE : View.GONE);
                holder.tvOrderPay.setVisibility(operation.contains("1") ? View.VISIBLE : View.GONE);
                holder.tvConfirmReceived.setVisibility(operation.contains("2") ? View.VISIBLE : View.GONE);
                holder.tvNotifySend.setVisibility(operation.contains("3") ? View.VISIBLE : View.GONE);
                holder.tvOrderEvaluation.setVisibility(operation.contains("4") ? View.VISIBLE : View.GONE);
                holder.tvBrowseDetails.setVisibility(operation.contains("5") ? View.VISIBLE : View.GONE);
                holder.tvApplyRefund.setVisibility(operation.contains("6") ? View.VISIBLE : View.GONE);
                holder.tvRefundDetail.setVisibility(operation.contains("7") ? View.VISIBLE : View.GONE);
            }
            if (!TextUtils.isEmpty(bean.getDeputyPic())) {
                String[] split = bean.getDeputyPic().split(",");
                holder.rvProductPic.setAdapter(new PicAdapter(holder, split));
                holder.rvProductPic.setLayoutManager(new GridLayoutManager(getContext(), 4));
            }

            holder.itemView.setOnClickListener(v -> openOrderDetails(holder.getAdapterPosition()));
            holder.item_view.setOnClickListener(v -> openOrderDetails(holder.getAdapterPosition()));
            holder.tvOrderCancel.setOnClickListener(v -> getPresenter().cancelOrder(bean.getID()));
            holder.tvOrderPay.setOnClickListener(v -> ChoosePayTypeActivity.start(getContext(), bean.getID()));
            holder.tvConfirmReceived.setOnClickListener(v -> confirmDialog(bean.getID()));
            holder.tvNotifySend.setOnClickListener(v -> {

            });
            holder.tvOrderEvaluation.setOnClickListener(v -> CommitCommentActivity.start(getContext(), bean.getID()));
            holder.tvBrowseDetails.setOnClickListener(v -> OrderDetailsActivity2.start(getContext(), bean.getID()));
            holder.tvApplyRefund.setOnClickListener(v -> ApplyRefundActivity.start(getContext(), bean.getID()));
            holder.tvRefundDetail.setOnClickListener(v -> RefundDetailsActivity.start(getContext(), bean.getID()));
        }

        public void confirmDialog(String id) {
            new CustomDialog.Builder(getActivity()).setTitle("提示")
                    .setContent("是否确认操作")
                    .setListener(new CustomDialog.OnButtonClickListener() {
                        @Override
                        public void onConfirm(Dialog dialog) {
                            getPresenter().confirmReceipt(id);
                            dialog.dismiss();
                        }

                        @Override
                        public void onCancel(Dialog dialog) {
                            dialog.dismiss();
                        }
                    }).build().show();
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {

            @BindView(R.id.tv_order_sn)
            TextView mTvOrderSn;
            @BindView(R.id.tv_order_status)
            TextView mTvOrderStatus;
            @BindView(R.id.tv_order_total_money)
            TextView mTvOrderTotalMoney;
            @BindView(R.id.tv_goods_num)
            TextView mTvGoodsNum;
            @BindView(R.id.tv_order_time)
            TextView mTvOrderTime;

            @BindView(R.id.item_view)
            View item_view;
            @BindView(R.id.rv_product)
            RecyclerView rvProductPic;  //商品图片列表

            @BindView(R.id.tv_order_cancel)
            TextView tvOrderCancel;
            @BindView(R.id.tv_order_pay)
            TextView tvOrderPay;
            @BindView(R.id.tv_order_shouhuo)
            TextView tvConfirmReceived;
            @BindView(R.id.tv_notify_send)
            TextView tvNotifySend;
            @BindView(R.id.tv_order_evaluation)
            TextView tvOrderEvaluation;
            @BindView(R.id.tv_browse_details)
            TextView tvBrowseDetails;
            @BindView(R.id.tv_apply_refund)
            TextView tvApplyRefund;
            @BindView(R.id.tv_refund_detail)
            TextView tvRefundDetail;

            Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    class PicAdapter extends RecyclerView.Adapter<PicAdapter.Holder> {
        OrderListAdapter.Holder mHolder;
        String[] mPic;

        public PicAdapter(OrderListAdapter.Holder holder, String[] pic) {
            mHolder = holder;
            mPic = pic;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(getLayoutInflater().inflate(R.layout.item_order_list_pic, parent, false));
            holder.itemView.setOnClickListener(v -> openOrderDetails(mHolder.getAdapterPosition()));
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            ImageUtils.showImage(getContext(), mPic[position], holder.mIvPicture);
        }

        @Override
        public int getItemCount() {
            return mPic.length > 4 ? 4 : mPic.length;
        }

        public class Holder extends RecyclerView.ViewHolder {
            @BindView(R.id.iv_picture)
            ImageView mIvPicture;

            Holder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    private void openOrderDetails(int adapterPosition) {
//        OrderDetailsActivity.start(getContext(), mList.get(adapterPosition).getComId());
        OrderDetailsActivity2.start(getContext(), mList.get(adapterPosition).getID());
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshEvent(RefreshEvent event) {/* Do something */
        getData(false);
    }
}
